﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace NewSeasonFinder
{
    public partial class ShowManage : Form
    {
        private ContextMenuStrip rightMouseButtonMenu;
        private const String STR_AddShow = "添加剧集";
        private const String STR_EditShow = "修改剧集";
        private const String STR_DelShow = "删除剧集";
        private const String STR_AddSeason = "添加季";
        private const String STR_DelSeason = "删除季";

        private XmlDocument xmlDoc;
        private bool isChanged;

        /// <summary>
        /// 初始化
        /// </summary>
        public ShowManage()
        {
            InitializeComponent();
            xmlDoc = ShowXml.Read();
            xmlDoc = ShowXml.ShowSort(xmlDoc);
            refreshTreeView();
            isChanged = false;
        }

        /// <summary>
        /// 生成右键菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeView1_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                rightMouseButtonMenu = new ContextMenuStrip();
                if (treeView1.SelectedNode != null)
                {
                    if (treeView1.SelectedNode.Level == 0)
                    {
                        //所选项为剧集
                        rightMouseButtonMenu.Items.Add(STR_EditShow);
                        rightMouseButtonMenu.Items.Add(STR_AddShow);
                        rightMouseButtonMenu.Items.Add(STR_DelShow);
                        rightMouseButtonMenu.Items.Add("-");
                        rightMouseButtonMenu.Items.Add(STR_AddSeason);
                    }
                    else if (treeView1.SelectedNode.Level == 1)
                    {
                        //所选为季
                        rightMouseButtonMenu.Items.Add(STR_AddSeason);
                        rightMouseButtonMenu.Items.Add(STR_DelSeason);
                    }
                }
                else
                {
                    rightMouseButtonMenu.Items.Add(STR_AddShow);
                }
                rightMouseButtonMenu.ItemClicked += new ToolStripItemClickedEventHandler(this.rightMouseButtonMenu_Click);
                rightMouseButtonMenu.Show(MousePosition);
            }
        }

        /// <summary>
        /// 右键菜单功能处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rightMouseButtonMenu_Click(object sender, ToolStripItemClickedEventArgs e)
        {
            switch (e.ClickedItem.Text)
            {
                case STR_AddShow: //添加剧集
                    AddShow();
                    break;
                case STR_EditShow:
                    EditShow();
                    break;
                case STR_DelShow:
                    DelShow();
                    break;
                case STR_AddSeason:
                    AddSeason();
                    break;
                case STR_DelSeason:
                    DelSeason();
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// 确定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_Ok_Click(object sender, EventArgs e)
        {
            if (isChanged)
            {
                xmlDoc = ShowXml.ShowSort(xmlDoc);
                ShowXml.Save(xmlDoc);
            }
            this.Close();
        }

        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_Cancel_Click(object sender, EventArgs e)
        {
            if (isChanged == true)
            {
                switch (MessageBox.Show("所做修改尚未保存，是否现在保存？", "", MessageBoxButtons.YesNoCancel))
                {
                    case System.Windows.Forms.DialogResult.Yes:
                        {
                            xmlDoc = ShowXml.ShowSort(xmlDoc);
                            ShowXml.Save(xmlDoc);
                        }
                        break;
                    case System.Windows.Forms.DialogResult.Cancel:
                        {
                            return;
                        }
                    default:
                        break;
                }
            }
            this.Close();
        }

        /// <summary>
        /// 刷新TreeView
        /// </summary>
        private void refreshTreeView()
        {
            XmlNode xn_root = xmlDoc.SelectSingleNode(NameStrings.SHOWS);
            
            int tree_node_number = 0;
            int xml_node_number = 0;

            //基于A,B个已排序的队列,从A中去除A不存在于B的节点,向A增加B中不存在于A的节点
            while (tree_node_number < treeView1.Nodes.Count || xml_node_number < xn_root.ChildNodes.Count)
            {
                string tn_name = "";
                string xn_name = "";
                //如果读到超过treeView长度的xml节点(说明xml比tree的长度长,且多出的节点在xml的后部)
                if (tree_node_number >= treeView1.Nodes.Count)
                {
                    //将xml节点加入tree
                    xn_name = ShowXml.GetShowFullName(xn_root.ChildNodes[xml_node_number], ":");
                    treeView1.Nodes.Add(xn_name, xn_name);
                    treeView1.Nodes[tree_node_number].Tag = xn_root.ChildNodes[xml_node_number];
                    refreshShowNode(treeView1.Nodes[tree_node_number]);
                    //此时tree已经增加了节点,所以number增加
                    tree_node_number++;
                    //同时继续向下读取node节点
                    xml_node_number++;
                    continue;
                }

                //如果tree的长度已经大于xml长度,说明tree存在已经被删除的节点
                if (xml_node_number >= xn_root.ChildNodes.Count)
                {
                    //则移除tree中应该被删除的节点
                    treeView1.Nodes.RemoveAt(tree_node_number);
                    continue;
                }

                //对比对应的节点值
                tn_name = treeView1.Nodes[tree_node_number].Name;
                xn_name = ShowXml.GetShowFullName(xn_root.ChildNodes[xml_node_number],":");

                int result = tn_name.CompareTo(xn_name);

                if (result == 0)
                {
                    //如果节点值相同,为相同节点,刷新tree中相应节点信息,继续向下访问
                    treeView1.Nodes[tree_node_number].Tag = xn_root.ChildNodes[xml_node_number];
                    refreshShowNode(treeView1.Nodes[tree_node_number]);//刷新剧集季
                    tree_node_number++;
                    xml_node_number++;
                }
                else if (result > 0)
                {
                    //如果存在tree没有而xml有的节点,则把该节点插入tree的当前位置
                    treeView1.Nodes.Insert(tree_node_number, xn_name, xn_name);
                    treeView1.Nodes[tree_node_number].Tag = xn_root.ChildNodes[xml_node_number];
                    refreshShowNode(treeView1.Nodes[tree_node_number]);//刷新剧集季
                    //继续访问tree和xml的下一个节点
                    tree_node_number++;
                    xml_node_number++;
                }
                else
                {
                    //如果存在tree有而xml没有的节点,则把该节点从tree删除
                    treeView1.Nodes.RemoveAt(tree_node_number);
                }
            }
        }

        /// <summary>
        /// 刷新一个剧集节点,将季挂树
        /// </summary>
        /// <param name="tn_show">所选剧集节点</param>
        private void refreshShowNode(TreeNode tn_show)
        {

            XmlNode xn_show = (XmlNode)tn_show.Tag;
            List<int> seasonList = new List<int>();

            foreach (XmlNode xn_season in xn_show.SelectNodes(NameStrings.SEASON))
            {
                string season = ShowXml.GetSeason(xn_season);
                seasonList.Add(Convert.ToInt32(season));
            }
            int i = 0;
            int j = 0;

            //基于A,B个已排序的队列,从A中去除A不存在于B的节点,向A增加B中不存在于A的节点
            while (i < tn_show.Nodes.Count || j < seasonList.Count)
            {
                //如果读到超过treeView长度的xml节点(说明xml比tree的长度长,且多出的节点在xml的后部)
                if (i >= tn_show.Nodes.Count)
                {
                    tn_show.Nodes.Add(seasonList[j].ToString(), string.Format("Season{0}", seasonList[j].ToString()));
                    i++;
                    j++;
                    continue;
                }

                //如果tree的长度已经大于xml长度,说明tree存在已经被删除的节点
                if (j >= seasonList.Count)
                {
                    tn_show.Nodes.RemoveAt(i);
                    continue;
                }

                //如果节点值相同,为相同节点,继续向下访问
                if (Convert.ToInt32(tn_show.Nodes[i].Name) == seasonList[j])
                {
                    i++;
                    j++;
                }
                else if (Convert.ToInt32(tn_show.Nodes[i].Name) > seasonList[j])
                {
                    //如果存在tree没有而xml有的节点,则把该节点插入tree的当前位置
                    tn_show.Nodes.Insert(i, seasonList[j].ToString(), string.Format("Season{0}", seasonList[j].ToString()));
                    i++;
                    j++;
                }
                else
                {
                    //如果存在tree有而xml没有的节点,则把该节点从tree删除
                    tn_show.Nodes.RemoveAt(i);
                }
            }
        }

        private void treeView1_MouseDown(object sender, MouseEventArgs e)
        {
            treeView1.SelectedNode = null;
        }

        private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            treeView1.SelectedNode = e.Node;
        }
        
        /// <summary>
        /// Add a new TV Show
        /// </summary>
        private void AddShow()
        {
            ShowEditor showAdder = new ShowEditor(xmlDoc);
            if (showAdder.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                isChanged = true;
                //SeasonAdd seasonAdder = new SeasonAdd(xmlDoc, xn_show);
                //seasonAdder.ShowDialog();
                refreshTreeView();
            }
        }

        private void DelShow()
        {
            int result = ShowXml.DelShow(xmlDoc, (XmlNode)treeView1.SelectedNode.Tag);
            if (result != 0)
            {
                string error = "未知错误";
                switch (result)
                {
                    case -3://剧集不存在
                        error = "要删除的剧集已不存在";
                        break;
                    default:
                        error = "未知错误";
                        break;
                }
                MessageBox.Show(error, "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                isChanged = true;
                refreshTreeView();
            }
        }

        private void EditShow()
        {
            ShowEditor showEditor = new ShowEditor(xmlDoc, (XmlNode)treeView1.SelectedNode.Tag);
            if (showEditor.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                isChanged = true;
                refreshTreeView();
            }
        }

        private void AddSeason()
        {
            XmlNode xn_show = null;
            int lastSeason = 0;
            if (treeView1.SelectedNode.Level == 0)
            {
                //所选项为剧集
                xn_show = (XmlNode)treeView1.SelectedNode.Tag;
                if (treeView1.SelectedNode.Nodes.Count != 0)
                {
                    lastSeason = Convert.ToInt32(treeView1.SelectedNode.LastNode.Name);
                }
            }
            else
            {
                //所选为季
                xn_show = (XmlNode)treeView1.SelectedNode.Parent.Tag;
                lastSeason = Convert.ToInt32(treeView1.SelectedNode.Parent.LastNode.Name);
            }

            SeasonAdd seasonAdder = new SeasonAdd(xmlDoc, xn_show, lastSeason);
            if (seasonAdder.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                isChanged = true;
                refreshTreeView();
            }
        }
        private void DelSeason()
        {
            int result = ShowXml.DelSeason(xmlDoc, (XmlNode)treeView1.SelectedNode.Parent.Tag, Convert.ToInt32(treeView1.SelectedNode.Name));
            if (result != 0)
            {
                string error = "未知错误";
                switch (result)
                {
                    case -3://剧集不存在
                        error = "要删除的剧集已不存在";
                        break;
                    case -5://季不存在
                        error = "要删除的季已不存在";
                        break;
                    default:
                        error = "未知错误";
                        break;
                }
                MessageBox.Show(error, "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                isChanged = true;
                refreshTreeView();
            }
        }

        private void buttonAddShow_Click(object sender, EventArgs e)
        {
            AddShow();
        }

        private void buttonAddSeason_Click(object sender, EventArgs e)
        {
            if (treeView1.SelectedNode != null)
            {
                AddSeason();
            }
        }
        
        private void buttonDelete_Click(object sender, EventArgs e)
        {
            if (treeView1.SelectedNode != null)
            {
                if (treeView1.SelectedNode.Level == 0)
                {
                    DelShow();
                }
                else
                {
                    DelSeason();
                }
            }
        }
    }
}
